// AddBinary.cpp : Defines the entry point for the console application.
//
//
//Given two binary strings, return their sum (also a binary string).

//For example,
//a = "11"
//b = "1"
//Return "100".


#include "stdafx.h"
#include <string>
using namespace std;



string addBinary(string a, string b) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
	string strResult;
	if(a.empty() || b.empty()) return strResult;
	string prefixZeros;
	int nDiff = abs((int)a.length() - (int)b.length());
	for(int i = 0; i<nDiff; i++)
	{
		prefixZeros+="0";

	}
	if(a.length()< b.length())
		a=prefixZeros+a;
	else if(a.length() > b.length())
		b=prefixZeros+b;
	
	int nLen =(int)a.length();
	char carrier = '0';
	for(int i= nLen -1; i>=0; i--)
	{
		if((a.at(i)=='1' && b.at(i) == '1'))
		{
			if(carrier == '0')
			{
				strResult = "0"+strResult;
			}
			if(carrier == '1')
			{
				strResult = "1"+strResult;
			
			}
			carrier = '1';
		}
		if(a.at(i)=='0' && b.at(i)=='0')
		{
			if(carrier == '0')
			{
				strResult = "0"+strResult;
			}
			if(carrier == '1')
			{
				strResult = "1"+strResult;
			
			}
			carrier = '0';
		}
		if((a.at(i)=='0' && b.at(i)=='1') || a.at(i)=='1' && b.at(i)=='0')
		{
			if(carrier == '0')
			{
				strResult = "1"+strResult;
				carrier = '0';

			}
			if(carrier == '1')
			{
				strResult = "0"+strResult;
				carrier = '1';
			}

		}
	}
	if(carrier == '1')
		strResult = "1"+ strResult;

	return strResult;
        
}

int _tmain(int argc, _TCHAR* argv[])
{
	string strRet = addBinary("11", "1");
	return 0;
}

